<template>
  <div>
    <!-- 头部 -->
    <a-form
      ref="searchRef"
      :rules="rules"
      :model="searchForm"
      :hideRequiredMark="true"
      style="margin-bottom: 20px"
    >
      <a-row>
        <a-col :span="6">
          <a-form-item label="上线时间：">
            <a-range-picker @change="panelChange"></a-range-picker>
          </a-form-item>
        </a-col>
        <a-col :span="4" :offset="1">
          <a-form-item name="saleValue" label="状态：">
            <a-select
              ref="select"
              v-model:value="searchForm.status"
              @focus="focus"
              @change="handleChange"
              placeholder="请选择"
              allowClear
            >
              <a-select-option
                v-for="item in saleStatusOptions"
                :value="item.id"
                :key="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="1">
          <a-form-item name="saleValue" label="关键字">
            <a-input
              placeholder="根据编号，权益卡名称，权益卡类型查询"
              v-model:value="searchForm.keyWord"
              allowClear
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="4" :offset="1">
          <a-button type="primary" @click="search" class="d-a-center"
            >搜索</a-button
          ></a-col
        >
      </a-row>
    </a-form>

    <!-- 列表 -->
    <a-table
      :columns="columns"
      :row-selection="rowSelection"
      :data-source="list"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #status="{ record }">
        <div>
          {{ ["待审核", "已通过", "已拒绝"][record.status] }}
        </div>
      </template>
      <template #stack="{ record, index }">
        <div
          v-has="{ a: $route, b: 2 }"
          @click="changeStack(record.status, index, record.id)"
        >
          <a-switch
            v-model:checked="record.status"
            :checkedValue="0"
            :unCheckedValue="1"
          />
        </div>
      </template>
      <template #operation="{ record }">
        <a-button
          type="link"
          @click="handleLook(record)"
          v-has="{ a: $route, b: 1 }"
          >查看</a-button
        >
        <a-button
          type="link"
          danger
          v-if="record.status == 0"
          @click="handleLook(record, '审核')"
          v-has="{ a: $route, b: 2 }"
          >审核</a-button
        >
      </template>
    </a-table>

    <div>
      <!-- 新增-->
      <a-modal
        width="800px"
        v-model:visible="visible"
        :title="title"
        :okText="title == '查看' ? '' : 通过"
        cancelText="拒绝"
        @ok="saveRight(1)"
        @cancle="storeVisible = true"
      >
        <a-form
          ref="formRef"
          style="padding-top: 20px"
          :model="orderForm"
          :rules="orderRule"
          :hideRequiredMark="true"
          :label-col="labelCol"
        >
          <a-row :gutter="20">
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="name" label="权益卡名称">
                <!-- <a-input
                v-model:value="orderForm.serviceName"
                placeholder="请输入服务名称"
              ></a-input> -->
                <a-input
                  v-model:value="orderForm.name"
                  placeholder="请输入权益卡名称"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="type" label="权益卡类型">
                <a-input
                  v-model:value="orderForm.type"
                  placeholder="请输入权益卡类型。ex：企业，个人用户"
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="20">
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="num" label="发放数量">
                <a-input
                  maxLength="10"
                  v-model:value="orderForm.num"
                  placeholder="请输入权益卡数量"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="businessPrice" label="营业额">
                <a-input
                  v-model:value="orderForm.businessPrice"
                  placeholder="请输入合计产生的营业额"
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="20">
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="activateDay" label="激活时间">
                <span>
                  {{ orderForm.createdAt.slice(0, 11) }}-{{
                    orderForm.activateTime.slice(0, 11)
                  }}
                </span>
              </a-form-item>
            </a-col>
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="useDay" label="使用时间">
                <span>
                  {{ orderForm.createdAt.slice(0, 11) }}-{{
                    orderForm.useTime.slice(0, 11)
                  }}
                </span>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="20">
            <!-- <a-col :span="12" :lg="12" :xs="10">
            <a-form-item name="scheduleTime" label="服务时间">
              <a-date-picker show-time  valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="orderForm.scheduleTime" />
            </a-form-item>
          </a-col> -->
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="" label="提交时间">
                <a-input
                  v-model:value="orderForm.createdAt"
                  placeholder=""
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="20">
            <!-- <a-col :span="12" :lg="12" :xs="10">
            <a-form-item name="scheduleTime" label="服务时间">
              <a-date-picker show-time  valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="orderForm.scheduleTime" />
            </a-form-item>
          </a-col> -->
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="remark" label="备注信息">
                <a-input
                  maxLength="100"
                  v-model:value="orderForm.remark"
                  placeholder="请输入备注信息"
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12" :lg="12" :xs="10">
              <!--  -->
              <a-form-item
                name="remark"
                :label="
                  '居家护理(' +
                  serviceList.length +
                  '选' +
                  orderForm.useNum +
                  ')'
                "
              >
                <span v-for="item in serviceList" :key="item.id">{{
                  item.comboServiceName + "*" + item.comboServiceCount + ","
                }}</span>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <template #footer>
          <div class="d-j-around">
            <a-button
              v-if="title == '查看'"
              @click="visible = false"
              class="d-a-center"
              >关闭</a-button
            >
            <a-button
              v-if="title != '查看'"
              type="primary"
              @click="storeVisible = true"
              class="d-a-center"
              >拒绝</a-button
            >
            <a-button
              v-if="title != '查看'"
              type="primary"
              @click="saveRight(1)"
              class="d-a-center"
              >通过</a-button
            >
          </div></template
        >
      </a-modal>
      <!-- 拒绝原因 -->
      <a-modal
        :visible="storeVisible"
        @ok="saveRightCancel(2)"
        @cancel="storeVisible = false"
        okText="确定"
        title="拒绝原因"
      >
        <a-form ref="storeFormRef">
          <a-form-item name="consumableLists">
            <a-input v-model:value="cancelCause" placeholder=""></a-input>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>
<script>
import {
  reactive,
  ref,
  computed,
  createVNode,
  watch,
  toRefs,
  unref,
  toRaw,
  isReactive,
  toRef,
} from "vue";
import {
  CheckOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { Modal, message } from "ant-design-vue";
import {
  selectAllConsumableBag,
  upOrDownConsumableBag,
  selectAllDetail,
  updateAndAddConsumableBag,
  deleteConsumableBag,
} from "@/api/consume/index.js";
import * as api from "@/api/market/rights.js";
// import { selectAllService, selectAllType } from "@/api/service/index.js";
import { deleteObjBlank } from "@/assets/js/common.js";
import { useModal } from "@/hooks"
// import * as api from "@/api/service/index.js";
export default {
  setup() {
    const searchRef = ref("");
    const formRef = ref("");

    const data = reactive({
      storeVisible: false,
      cancelCause: "",
      editing: true,
      title: "创建",
      serveVisible: false,
      jihuoVisible: false,
      list: [],
      listRights: [], //明细列表
      loading: true,
      visible: false,
      serviceList: [], //分类列表
      detaiList: [],
      consumables: [], //默认绑定ID即可
      statusAct: 0,
      searchForm: {},
      searchForm1: {},
      number: "", //当前机构编号
      typeList: [],
      servicesList: [],
      orderForm: {},
      serviceForm: {},
      value: [], //分类-这个远程加载的数据好像不可以哎
      defaultValue: [],
      orderAct: 1, //1线上 2线下
      tabs: [
        {
          title: "已激活",
          id: 1,
        },
        {
          title: "未激活",
          id: 2,
        },
        {
          title: "已冻结",
          id: 3,
        },
      ],
    });
    const columns = [
      {
        title: "编号",
        dataIndex: "number",
        className: "table",
      },
      {
        title: "权益卡名称",
        dataIndex: "name",
        className: "table",
      },
      {
        title: "权益卡类型",
        dataIndex: "type",
        className: "table",
      },
      {
        title: "发放数量",
        dataIndex: "num",
        className: "table",
      },
      {
        title: "营业额",
        dataIndex: "activateNum",
        className: "table",
      },
      {
        title: "提交时间",
        dataIndex: "createdAt",
        className: "table",
      },
      {
        title: "状态",
        dataIndex: "status",
        className: "table",
        slots: {
          customRender: "status",
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        className: "table",
        slots: {
          customRender: "operation",
        },
      },
    ];
    const modalTitle = ref("新增耗材");
    const rules = {
      //  portValue: [{ required: true, message: '请选择端口!', trigger: 'change'}],
      //  inputValue: [{ required: true, message: '请输入搜索内容!', trigger: 'blur'}],
    };
    const rules1 = {
      name: [
        {
          required: true,
          message: "请输入耗材名称!",
        },
      ],
      sellPrice: [
        {
          required: true,
          message: "请输入销售价!",
        },
      ],
      serviceId: [
        {
          required: true,
          message: "请输入服务类型!",
        },
      ],
      typeId: [
        {
          required: true,
          message: "请输入服务分类!",
        },
      ],
      bazaarPrice: [
        {
          required: true,
          message: "请输入市场价格!",
        },
      ],
      bagNumber: [
        {
          required: true,
          message: "请输入耗材编号!",
        },
      ],
      // value: [{ required: true, message: "请选择耗材分类!" }],
    };

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    const pages = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });

    const saleStatusOptions = reactive([
      {
        name: "全部",
        id: "",
      },
      {
        name: "待审核",
        id: "0",
      },
      {
        name: "已通过",
        id: "1",
      },
      {
        name: "已拒绝",
        id: "2",
      },
    ]);
    const consumeOptions = reactive([
      {
        name: "耗材名称",
        id: 1,
      },
      {
        name: "耗材分类",
        id: 1,
      },
    ]);
    const delListId = ref([]); //删除数组ID集合
    const chooseStatus = (status, index) => {
      data.statusAct = index;
      data.searchForm.status = status;
      page.current = 1;
      init();
    };
    // 查询
    const search = () => {
      page.current = 1;
      init();
    };

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ["10", "20", "30"],
      showTotal: (total, range) => {
        return "共" + total + "条";
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true,
    }));

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, "当前分页");
      page.current = pagination.current;
      page.pageSize = pagination.pageSize;

      // 请求列表接口
      init();
    };

    // 新增
    const add = () => {
      data.editing = true;
      data.title = "创建";
      data.visible = true;
    };

    const handleLook = (item, title = "查看") => {
      data.editing = false;
      data.title = title;
      data.number = item.id;
      api
        .selectCardTempById({
          id: item.id,
        })
        .then((r) => {
          if (r.success) {
            data.visible = true;
            data.orderForm = {
              ...r.object,
            };
            data.serviceList = [...(r.object.goodTempList || [])];
          }
        });
    };
    const edit = async (item) => {
      if (item.add) return;
      data.servicesList.map((m) => {
        if (m.id == item.id) {
          m.add = true;
          data.serviceList.push(m);
        }

        return m;
      });
    };
    const Typename = (id) => {
      let item = data.typeList.find((el) => el.id == id);
      console.log(item, "分类名字是");
      return item;
    };

    const serviceName = (id) => {
      let list = data.serviceList.find((el) => el.id == id);
      if (list.serviceName) {
        // return list.serveName;
        return list;
      }
    };
    const changeOrder = (e) => {
      if (e == data.orderAct) return;
      data.orderAct = e;
      pages.current = 1;
      initRightList();
    };
    const save = () => {
      if (data.value.length != 3) {
        message.error("请选择具体服务");
        return;
      }
      data.orderForm.typeId = data.value[0];
      data.orderForm.secondTypeId = data.value[1];
      data.orderForm.serviceId = data.value[2];
      console.log(data.orderForm, "表单内容是");

      formRef.value.validate().then(async () => {
        let arr = [];
        // 查找耗材包明细内容两个数组比较
        data.detaiList.forEach((el) => {
          data.consumables.forEach((item) => {
            if (item == el.id) {
              arr.push(el);
            }
          });
        });
        if (data.value.length == 0) {
          message.error("请选择耗材分类!!!");
          return;
        }

        data.orderForm.consumables = arr;
        let res = await updateAndAddConsumableBag(data.orderForm);
        if (res.success) {
          init();
          message.success("新增成功");
          data.visible = false;
        }
      });
    };
    const addServeVisible = () => {
      pages.current = 1;
      data.serveVisible = true;
      initService();
    };
    // 删除
    const del = (key) => {
      const {closeModal} = useModal.confirm({
        title: () => "你确定删除当前项吗?",
        icon: () => createVNode(QuestionCircleOutlined),
        content: () =>
          createVNode(
            "div",
            {
              style: "color:red;",
            },
            "删除当前数据后不可恢复，请谨慎考虑。"
          ),
        onOk: async () => {
          let res = await deleteConsumableBag([Number(key)]);
          if (res.success) {
            message.success("删除成功");
            init();
            closeModal()
          }
        },
        class: "test",
      });
    };
    const selectConsume = (e) => {
      console.log(e);
    };
    const selectService = (e) => {
      // console.log(e, "服务类型");s
    };
    const selectType = (e) => {};

    // 全选反选
    const rowSelection = ref({
      checkStrictly: false,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(
          `selectedRowKeys: ${selectedRowKeys}`,
          "selectedRows: ",
          selectedRows
        );
        delListId.value = selectedRowKeys;
      },
      onSelect: (record, selected, selectedRows) => {
        //console.log(record, selected, selectedRows,'选择多项');
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        //console.log(selected, selectedRows, changeRows,'全选操作');
        // 数组项
      },
    });
    // 删除多项
    const listDel = () => {
      const {closeModal} = useModal.confirm({
        title: "确定删除所选内容项吗?",
        icon: createVNode(ExclamationCircleOutlined),
        content: "删除后将不可恢复，请谨慎操作。",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk: async () => {
          console.log(delListId.value);
          let data = delListId.value.map((el) => (el = Number(el)));

          let res = await deleteConsumableBag(data);
          if (res.success) {
            message.success("删除成功");
            init();
            closeModal()
          }
        },
        
      });
    };

    // 是否上下架 就把原来的状态改变下就行，传递下当前项的耗材ID即可，
    const changeStack = (checked, index, id) => {
      console.log(page.pageNum);
      console.log(checked, index, "是否上下架");
      let title = checked == 0 ? "上架" : "下架";
      // 弹框提示？确定上下架吗
      const {closeModal} = useModal.confirm({
        title: () => `确定${title}当前耗材包吗?`,
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          let res = await upOrDownConsumableBag(id);
          if (res.success) {
            data.list[index].status = Number(checked);
            init();
            closeModal()

          }
        },
        onCancel() {
          let flag = checked == 0 ? 1 : 0;
          data.list[index].status = flag;
          closeModal()
        },
        class: "test",
      });
    };

    init();
    const handleSearch = () => {
      initService();
    };
    const saveRightCancel = (v) => {
      if (!data.cancelCause) {
        message.error("请输入原因");
        return;
      }
      saveRight(2);
    };
    const saveRight = (v) => {
      let obj = {
        id: data.number,
        status: v,
      };
      if (v == 2) {
        obj.cancelCause = data.cancelCause;
      }
      console.log("obj", obj);
      // debugger;
      api
        .updateCardTempStatus({
          ...obj,
        })
        .then((r) => {
          if (r.success) {
            message.success("操作成功");
            data.visible = false;
            data.storeVisible = false;
            init();
          }
        });
    };
    async function initService() {
      deleteObjBlank(data.serviceForm);
      api
        .selectServicesByParentIdAndName({
          id: 1,
          ...data.serviceForm,
          ...{
            pageNum: pages.current,
            pageSize: pages.pageSize,
          },
        })
        .then((r) => {
          data.servicesList = r.object.list.map((m) => {
            return {
              key: m.id,
              add: false,
              ...m,
              num: 1,
            };
          });
          pages.total = r.object.total;
          data.visible = true;
        });
    }
    async function initRightList() {
      let obj = {
        pageNum: pages.current,
        pageSize: pages.pageSize,
        status: data.orderAct - 1,
        number: data.number, //机构编号
        ...data.searchForm1,
      };
      let res = await api.selectUserCardByPowerNumber(obj);
      if (res.success) {
        res.object.list.map((el) => (el.key = el.id));
        data.listRights = res.object.list;
        // data.list.forEach(el=>{
        // })
        data.loading = false;
        pages.total = res.object.total;
      }
    }
    async function init() {
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        ...data.searchForm,
      };
      let res = await api.selectPowerCardList(obj);
      if (res.success) {
        res.object.list.map((el) => (el.key = el.number));
        data.list = res.object.list;
        // data.list.forEach(el=>{
        // })
        data.loading = false;
        page.total = res.object.total;
      }
    }

    const closelog = (e, id) => {
      data.serviceList.splice(e, 1);
    };
    const cancleOrder = (v) => {
      data[v] = false;
    };

    const panelChange = (date, dateString) => {
      data.searchForm.startTime = dateString[0];
      data.searchForm.endTime = dateString[1];
    };

    const loadData = async (selectedOptions) => {
      console.log("点击了选择", selectedOptions);

      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true; // load options lazily
      // 二级
      if (selectedOptions.length == 1) {
        let obj = {
          parentId: targetOption.id,
        };
        let res1 = await selectAllType(obj);
        if (res1.success) {
          res1.object.map((el) => (el.isLeaf = false)); //id是string类型的
          targetOption.children = res1.object;
          data.typeList = [...data.typeList];
        }
      } else {
        // 三级
        let obj = {
          pageNum: 1,
          pageSize: 200,
          typeId: targetOption.id,
        };
        let res2 = await selectAllService(obj);
        if (res2.success) {
          res2.object.records.map((el) => (el.name = el.serveName));
          targetOption.children = res2.object.records;
          data.typeList = [...data.typeList];
        }
      }

      // let obj = {
      //   pageNum: 1,
      //   pageSize: 80,
      //   typeId: selectedOptions[0].id,
      // };
      // let res = await selectAllService(obj);
      // if (res.success) {
      //   targetOption.loading = false;
      //   res.object.records.map((el) => (el.name = el.serveName));
      //   targetOption.children = res.object.records;

      //   data.typeList = [...data.typeList];
      // }
    };
    return {
      ...toRefs(data),
      saleStatusOptions,
      consumeOptions,
      searchRef,
      modalTitle,
      formRef,
      rules,
      rules1,
      pagination,
      labelCol: {
        style: {
          width: "150px",
        },
      },
      wrapperCol: {
        span: 14,
      },
      columns,
      handleTableChange,
      search,
      add,
      del,
      save,
      edit,
      rowSelection,
      listDel,
      changeStack,
      serviceName,
      selectConsume,
      selectService,
      chooseStatus,
      Typename,
      selectType,
      loadData,
      addServeVisible,
      closelog,
      cancleOrder,
      changeOrder,
      handleLook,
      panelChange,
      handleSearch,
      saveRight,
      saveRightCancel,
    };
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
  },
};
</script>

<style scoped lang="less">
.act {
  color: #2a9d8f;
}
</style>
